import React, { useEffect, useState } from 'react';
import { Box, MainButton, MainColorType, makeToast, Radio, Text } from '@nova-hf/ui';
import { StepChildrenProps } from 'beta/containers/layout/StepWrapper';
import { formatPrice } from 'beta/utils/helpers';
import { parseMainColor } from 'beta/utils/typeGuards';
import { useRouter } from 'next/router';
import { ContractStatus, useContractsQuery, WhenToApply } from 'typings/graphql';
import { Trans, useTranslation } from 'utils/i18n';

import { CompareCards } from '../components/CompareCards';
import { CardItem, SellingCardItem } from '../components/SellingCardItem';
import useCompleteOrder from '../hooks/useCompleteOrder';
import useCompleteOrderForContract from '../hooks/useCompleteOrderForContract';

export enum ChangePlan {
  Product,
  Variant,
}

type ConfirmInternetAndAbroadProps = {
  currentContract?: CardItem;
  applicableVariantsAsCardItem?: CardItem;
  optionsAsCardItem?: CardItem;
  color?: MainColorType;
  changePlan?: ChangePlan;
  isCurrentlyPartOfAlltSaman?: boolean;
  jumping?: boolean;
} & StepChildrenProps;

export const ConfirmInternetAndAbroad = ({
  currentContract,
  applicableVariantsAsCardItem,
  optionsAsCardItem,
  color = 'pink',
  onPrev,
  isCurrentlyPartOfAlltSaman,
  jumping,
  changePlan = ChangePlan.Variant,
}: ConfirmInternetAndAbroadProps) => {
  const { t } = useTranslation('thjonustubreyting');
  const router = useRouter();

  const serviceId = typeof router?.query?.serviceId === 'string' ? router?.query?.serviceId : '';
  const customerId = typeof router?.query?.customerId === 'string' ? router?.query?.customerId : '';
  const contractId = typeof router.query.contractId === 'string' ? router.query.contractId : '';

  const [whenToApply, setWhenToApply] = useState<WhenToApply>(WhenToApply.Immediate);
  const { data } = useContractsQuery({
    variables: {
      input: {
        serviceId,
        customerId,
      },
    },
    skip: !serviceId || !customerId,
  });

  const contract = data?.contracts.contracts.find(
    (contract) =>
      contract.status === ContractStatus.Active || contract.status === ContractStatus.Pending,
  );

  const {
    onSubmit,
    orderComplete,
    creatOrderLoading,
    addCartItemsLoading,
    orderError,
    addToCartError,
  } =
    serviceId && jumping
      ? useCompleteOrder(whenToApply, serviceId, customerId, [
          ...(applicableVariantsAsCardItem ? [applicableVariantsAsCardItem] : []),
          ...(optionsAsCardItem ? [optionsAsCardItem] : []),
        ])
      : useCompleteOrderForContract(
          whenToApply,
          contractId ? contractId : contract?.id ? contract.id : '',
          customerId,
          [
            ...(applicableVariantsAsCardItem ? [applicableVariantsAsCardItem] : []),
            ...(optionsAsCardItem ? [optionsAsCardItem] : []),
          ],
        );
  const currentPriceNumber = currentContract?.price ?? 0;
  const newPriceNumber =
    (applicableVariantsAsCardItem?.price ?? 0) + (optionsAsCardItem?.price ?? 0);
  const currentPrice = formatPrice(currentPriceNumber);
  const newPrice = formatPrice(newPriceNumber);

  useEffect(() => {
    if (orderComplete) {
      makeToast.success(t('toast.orderSuccessfulTitle'), t('toast.orderSuccessfulDescription'));
      router.push({
        pathname: '/beta/[customerId]/thjonustur/[serviceId]',
        query: { customerId: customerId, serviceId: serviceId },
      });
    }
  }, [orderComplete]);

  useEffect(() => {
    if (orderError) makeToast.danger(t('toast.createOrderError'), orderError.message ?? '');
    if (addToCartError) makeToast.danger(t('toast.addingCartError'), addToCartError.message ?? '');
  }, [orderError, addToCartError]);

  const handleSubmit = () => {
    onSubmit();
  };

  return (
    <Box>
      <Text variant="h4" marginBottom={4}>
        {t('stadfesting.title')}
      </Text>
      <Box width={['100%', '10/12', '9/12', '6/12']}>
        {applicableVariantsAsCardItem?.id ? (
          <Text variant="pMediumRegular" marginBottom={5}>
            {currentPrice !== newPrice ? (
              <Trans
                i18nKey={
                  isCurrentlyPartOfAlltSaman
                    ? 'thjonustubreyting:stadfesting.goingFromAlltSamanDescription'
                    : currentPriceNumber > newPriceNumber
                    ? 'thjonustubreyting:stadfesting.reducingPriceDescription'
                    : 'thjonustubreyting:stadfesting.increasePriceDescription'
                }
              >
                ..
                {changePlan === ChangePlan.Variant ? { type: 'pakka' } : { type: 'þjónustuleið' }}
                <strong>{{ currentPrice }}</strong>
                <strong>{{ newPrice }}</strong>
                ...
              </Trans>
            ) : (
              t('stadfesting.description')
            )}
          </Text>
        ) : (
          <Text variant="pMediumRegular" marginBottom={5}>
            {t('stadfesting.addingAbroadPack')}
          </Text>
        )}
      </Box>

      <Box display="flex" flexDirection="column" gap={10}>
        {applicableVariantsAsCardItem && (
          <Box>
            <Text variant="subtitleBold" marginBottom={2}>
              {t('stadfesting.updatingCurrentContract')}
            </Text>
            {!isCurrentlyPartOfAlltSaman ? (
              <CompareCards
                color={color}
                currentContract={currentContract}
                newContract={applicableVariantsAsCardItem}
                isLoading={creatOrderLoading || addCartItemsLoading}
              />
            ) : (
              <Box width={{ sm: '11/12', md: '8/12', lg: '6/12' }}>
                <SellingCardItem
                  sellingCardItem={applicableVariantsAsCardItem}
                  priceUnit={t('internet.unit')}
                  color={color}
                  isDisabled={creatOrderLoading || addCartItemsLoading}
                  hasButton={false}
                />
              </Box>
            )}
          </Box>
        )}
        {optionsAsCardItem && (
          <Box>
            <Text variant="subtitleBold" marginBottom={2}>
              {t('stadfesting.addingAbroadContract')}
            </Text>
            <CompareCards
              newContract={optionsAsCardItem}
              isLoading={creatOrderLoading || addCartItemsLoading}
            />
          </Box>
        )}
      </Box>
      <Box marginTop={10}>
        <Text variant="subtitleBold" marginBottom={4}>
          {t('stadfesting.serviceChangeTitle')}
        </Text>
        <Box display="flex" flexDirection={['column', 'column', 'row']} gap={4}>
          <Box>
            <Radio
              isChecked={whenToApply === WhenToApply.Immediate}
              color={color}
              isDisabled={
                creatOrderLoading ||
                addCartItemsLoading ||
                !applicableVariantsAsCardItem?.isApplicable
              }
              onChange={() => setWhenToApply(WhenToApply.Immediate)}
            >
              <Text variant="pMediumBold" marginLeft={1}>
                {t('stadfesting.serviceChangeToday')}
              </Text>
            </Radio>
          </Box>
          <Box>
            <Radio
              isChecked={whenToApply == WhenToApply.StartOfNextCycle}
              color={color}
              onChange={() => setWhenToApply(WhenToApply.StartOfNextCycle)}
            >
              <Text variant="pMediumBold" marginLeft={1}>
                {t('stadfesting.serviceChangeNewMonth')}
              </Text>
            </Radio>
          </Box>
        </Box>
      </Box>

      <Box
        marginTop={14}
        display="flex"
        flexDirection={['column', 'column', 'row']}
        justifyContent="flex-end"
        gap={4}
      >
        <Box width={['100%', '100%', '5/12', '4/12']}>
          <MainButton
            text={t('buttons.prev')}
            colorScheme="white"
            isDisabled={creatOrderLoading || addCartItemsLoading}
            onClick={() => onPrev && onPrev()}
            dottedShadow="none"
          />
        </Box>
        <Box width={['100%', '100%', '5/12', '4/12']}>
          <MainButton
            colorScheme={parseMainColor(color, 'pink')}
            text={t('buttons.confirm')}
            icon="longArrowRight"
            isDisabled={creatOrderLoading || addCartItemsLoading}
            onClick={() => handleSubmit()}
            dottedShadow="none"
          />
        </Box>
      </Box>
    </Box>
  );
};
